/**
 * 审批页面
 * 跳转时传入 {
 *   approveType:'业务类型', 
 *   dictKey:'业务key',
 *   backPage:'返回页面'
 * }
 */
import React, { Component } from 'react';
import {
	StyleSheet, Text, View, TouchableOpacity,
	PixelRatio, Image, FlatList
} from "react-native";
import { NavigationEvents } from 'react-navigation';
import { GLOBAL } from '../../../../config/global';
import { style } from '../../../../theme/style';
import { Common } from '../../../../component/common/Common.js';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import { SinoNewOilApproveItem } from './_component/SinoNewOilApproveItem';
import { Tabs } from '../_component/tabs';
import NewOilApproveService from '../_common/service';
import StorageHelper from '../../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../../config/storage';

const scale = GLOBAL.SCALE;
export class SinoNewOilApproveListPage extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		const { params } = navigation.state;
		let { isCancel } = params || {};
		return {
			headerTitle: `中新油${isCancel ? '撤单' : '成交'}待审批`,
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../../imgs/goBackEmpty.png')} />),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	};

	constructor(props) {
		super(props);
		this.state = {
			tabIndex: props.navigation.state.params.approveIndex || 0,
			newLotData: [],  // 待审批
			status: 'loading',
			loadIcon: false,  // 下拉涮新的 图标
			alertShow: false,
			options: [],
			choice: {}
		}
		this.pageNo = 1;
		this.totalPage = 1;
		this.params = this.props.navigation.state.params;
		this.selectCancelList = false;
	}

	async componentWillMount() {
		await this.getSorage();
	}

	//获取业务组织
	async getSorage() {
		const userInfoJson = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
		const userInfo = JSON.parse(userInfoJson);
		this.setState({
			options: userInfo.corpInfoTOs || [],
			choice: this.state.choice.corpId ? this.state.choice : userInfo.corpInfoTOs[0]
		})
	}

	//获取待审批,已审批列表
	async _getListData(agentObj) {
		let { tabIndex, choice } = this.state;
		let tabInfo = {};
		tabInfo = NewOilApproveService.PROCESS_DEFINITION_KEY[tabIndex];
		let sendData = {
			onrefresh: false,
			pageNo: 1,
			corpId: choice.corpId
		}
		Object.assign(sendData, agentObj, tabInfo);
		// 过滤撤单
		if (this.params.isCancel) {
			sendData.processDefinitionKey = 'process_zxy_cancel_push';
		}
		this.setState({
			loadIcon: true
		})
		let responseData = await NewOilApproveService.getApproveList(this.params, tabIndex, sendData);
		this.setState({
			loadIcon: false
		});

		if (responseData) {
			this.totalPage = responseData.totalPage;
			if (sendData.onrefresh) {  // 加载
				this.setState({
					newLotData: this.state.newLotData.concat(responseData.rows),
					status: 'data'
				})
			} else { // 刷新
				this.setState({
					newLotData: responseData.rows,
					status: responseData.rows.length ? 'data' : 'empty'
				})
			}
		} else {
			this.setState({
				status: 'error'
			})
		}
	}

	// 下拉更新函数
	_isLoadRefresh() {
		this.pageNo = 1;
		this._getListData();
	}

	//上啦加载
	_loadData() {
		if (this.totalPage > this.pageNo) {
			this.pageNo++;
			this._getListData({
				pageNo: this.pageNo,
				onrefresh: true,
			});
		}
	}

	//tab 切换
	_tabs = (index) => {
		this.pageNo = 1;
		this.setState({
			tabIndex: index,
			status: 'loading',
			alertShow: false
		}, function () {
			this._getListData();
		})
	}

	//跳审批页面
	_goDetail = (paramsData, title) => {
		let { tabIndex, choice } = this.state;
		this.props.navigation.navigate(paramsData.resUrl, {
			paramsData,
			title,
			approveIndex: tabIndex,
			choice
		})
	}

	//数据加载出错回调
	_onErrorPress = () => {
		this.setState({
			status: 'loading'
		}, function () {
			this._getListData();
		})
	}

	// 一条数据
	_renderItem(list) {
		let { dictKey } = this.props.navigation.state.params || {};
		return (
			<SinoNewOilApproveItem
				tabIndex={this.state.tabIndex}
				itemInfo={list.item}
				dictKey={this.params.dictKey}
				isCancel={this.params.isCancel || false}
				goDetail={(paramsData, title) => {
					//代表是新油撤单进来的
					if (dictKey == "APP_ZXY_SAP_CANCEL_AUDIT_TASK") {
						paramsData.processDefinitionKey = "process_zxy_cancel_push";
					}
					this._goDetail(paramsData, title);
				}}
				approveType={this.params.approveType}
				choice={this.state.choice} />
		)
	}

	selectCancel = () => {
		this.selectCancelList = !this.selectCancelList;
		this._getListData();
	}

	_getSearchView() {
		/**
		 * 客户列表页隐藏头部，此处 搜索框和添加企业按钮作为头部展示
		 */
		return (
			<View style={styles.searchView}>
				<View style={styles.searchTypes}>
					<TouchableOpacity activeOpacity={1} style={styles.TitleOut} onPress={() => { navigatePress && navigatePress() }}>
						<Text style={styles.TitleText}>全部部门</Text>
						<Image style={styles.searchImg} source={require('../../../../imgs/Group.png')} />
					</TouchableOpacity>
					<TouchableOpacity activeOpacity={1} style={styles.TitleOut} onPress={() => { navigatePress && navigatePress() }}>
						<Text style={styles.TitleText}>商品</Text>
						<Image style={styles.searchImg} source={require('../../../../imgs/Group.png')} />
					</TouchableOpacity>
					<TouchableOpacity activeOpacity={1} style={styles.TitleOut} onPress={() => { navigatePress && navigatePress() }}>
						<Text style={styles.TitleText}>企业名称</Text>
						<Image style={styles.searchImg} source={require('../../../../imgs/Group.png')} />
					</TouchableOpacity>
				</View>
				<View style={styles.searchTimeView}>
					<Text style={styles.searchTime}>{'2019/09/01'}-{'2019/10/01'}</Text>
					<Image style={styles.searchTimeImg} source={require('../../../../imgs/global/timeSelectIcon.png')} />
				</View>
			</View>
		);
	}

	render() {
		let { tabIndex, companyName, newLotData, status, alertShow, choice, options } = this.state;
		const searchView = this._getSearchView();
		return (
			<View style={styles.container}>
				{/* {options.length > 1 ?
					<View style={styles.accountSelect}>
						<NewAccount fn={(val) => { this.setState({ alertShow: val }) }} choice={choice.corpName || ''} />
					</View> : null} */}
				<Tabs tabIndex={tabIndex} checkTab={(tab) => { this._tabs(tab); }} />

				{/* <View style={{ flexDirection: 'row', justifyContent: 'flex-end', paddingTop: 14 * scale, paddingRight: 10 * scale }}>
					<TouchableOpacity style={{ flexDirection: 'row', alignItems: 'center' }} activeOpacity={.8} onPress={() => { this.selectCancel() }}>
						<Image source={this.selectCancelList ? selectedImg : selectImg} style={[styles.selectIcon, this.selectCancelList ? null : { tintColor: '#cdcdcd' }]} />
						<Text style={[this.selectCancelList ? { color: style.color.themeColor } : { opacity: .8 }]}>仅看撤销</Text>
					</TouchableOpacity>
				</View> */}

				{/* {searchView} */}
				<NavigationEvents onWillFocus={async () => {
					await this.getSorage();
					await this._getListData();
				}} />
				{
					status == 'data' ? (
						<View style={styles.listBox}>
							<FlatList
								data={newLotData}
								renderItem={this._renderItem.bind(this)}
								refreshing={this.state.loadIcon}
								onRefresh={this._isLoadRefresh.bind(this)}
								onEndReachedThreshold={0.5}
								onEndReached={() => { this._loadData() }}
							/>
						</View>
					) : null
				}
				<PageStatusIndex status={status} emptyText="暂无记录" onErrorPress={this._onErrorPress} />
			</View >
		)
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray,
	},
	listItem: {
		width: '100%',
		paddingTop: 12 * scale,
		paddingBottom: 12 * scale,
		flexDirection: 'row',
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderBottomColor: style.color.gray,
	},
	leftImg: {
		width: 40 * scale,
		height: 40 * scale,
		marginLeft: 15 * scale
	},
	conent: {
		width: 265 * scale,
		paddingLeft: 15 * scale
	},
	rightText: {
		color: '#2F7BFF'
	},
	titleBox: {
		flexDirection: 'row',
		alignItems: 'center',
		marginBottom: 5 * scale
	},
	title: {
		fontSize: 14 * scale,
		color: '#222',

	},
	infoText: {
		fontSize: 12 * scale,
		color: '#8b8b8b'
	},
	elementImg: {
		width: 21 * scale,
		height: 14 * scale,
		marginLeft: 5 * scale
	},
	listBox: {
		flex: 1,
		backgroundColor: style.color.bgGray,
	},
	//列表item样式
	orderText: {
		fontSize: 12 * scale,
		color: '#8B8B8B'
	},
	orderVal: {
		fontSize: 12 * scale,
		color: '#000'
	},
	orderCol: {
		flexDirection: 'row',
		alignItems: 'center',
		height: 25 * scale,
		width: 175.5 * scale,
	},
	orderMain: {
		flexDirection: 'row',
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		flexWrap: 'wrap'
	},
	orderHeadPic: {},
	orderHeadText: {
		fontSize: 14 * scale,
		color: '#222',
		marginRight: 6 * scale,
		marginLeft: 6 * scale,
		flexWrap: 'wrap',
		// width: '70%'

	},
	orderHeadLeft: {
		height: 44 * scale,
		alignItems: 'center',
		flexDirection: 'row',
	},
	orderHead: {
		width: 351 * scale,
		borderBottomColor: '#e4e4e4',
		borderBottomWidth: 1 / PixelRatio.get(),
		height: 44 * scale,
		justifyContent: 'space-between',
		alignItems: 'center',
		flexDirection: 'row',
	},
	orderCell: {
		width: 375 * scale,
		backgroundColor: '#fff',
		alignItems: 'center',
		marginBottom: 12 * scale,
	},
	order: {
		width: 351 * scale,
	}, conImage: {
		width: 20 * scale,
		height: 14 * scale,
		marginLeft: 5 * scale,
	}, forwardText: {
		paddingTop: 2 * scale,
		marginTop: 2 * scale,
		marginLeft: 6 * scale,
		width: 30 * scale,
		height: 16 * scale,
		backgroundColor: '#49CAFF',
		color: '#FFFFFF',
		fontSize: 11 * scale,
		textAlign: 'center',
		borderRadius: 4 * scale,
	},
	statusText: {
		fontSize: 13 * scale,
		color: style.color.themeColor,
	},
	TitleOut: {
		width: '33%',
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center'
	},
	TitleText: {
		color: '#0E7FFD',
		fontSize: 12 * scale
	},
	searchView: {
		flexDirection: 'column',
		position: 'absolute',
		left: 8 * scale,
		top: 66 * scale,
	},
	searchTypes: {
		flexDirection: 'row',
		width: 359 * scale,  // 726
		height: 40 * scale,
		backgroundColor: '#fff',
		borderRadius: 6 * scale,
	},
	searchImg: {
		tintColor: style.color.themeColor,
		marginLeft: 3 * scale
	},
	searchTime: {
		textAlign: 'right',
		color: '#000',
		fontSize: 12 * scale,
	},
	searchTimeView: {
		marginTop: 18 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'flex-end'
	},
	searchTimeImg: {
		tintColor: '#848A96',
		width: 16 * scale,
		height: 19 * scale,
		marginLeft: 6 * scale
	},
	selectIcon: {
		width: 14 * scale,
		height: 14 * scale,
		marginRight: 8 * scale
	},
	accountSelect: {
		backgroundColor: style.color.themeColor,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center'
	}
})